<?php
/**
 * @author ykm 2016-01-19
 * @describe 短信接口请求
 */
class erpapi_sms_request_sms extends erpapi_sms_request_abstract
{

    #发送一条短信
    public function sendOne($sdf,$queue=false)
    {
        $args = func_get_args();array_pop($args);
        $channel_id = serialize($this->__channelObj->channel['account']);
        
        
        //短信签名验证
        preg_match('/\【(.*?)\】$/',$sdf['replace']['msgsign'],$filtcontent1);
        
        if ($filtcontent1) {
            $signRs = $this->newOauth(array('sms_sign'=>$filtcontent1[0]));

            if ($signRs['rsp'] == 'fail') {
                $msg = '短信签名错误，原因：'.$signRs['data'].($signRs['res']=='1000'?',请重新解绑登陆':'').'！';
                $this->writeSmslog($sdf['phones'], $sdf['content'], $msg, 0);
                return $signRs;
            }
        }
        //剩余短信条数,
        $info = $this->getUserInfo();

        $smsAmount = ceil(taoexlib_utils::utf8_strlen($sdf['content']) / taoexlib_utils::SINGLE_SMS_LENGTH);
        if ('succ' == $info['rsp']) {
            if($info['data']['month_residual'] >= $smsAmount) {
                $result = $this->sendByTmpl($sdf);
                return $result;
            } else {
                $msg = '剩余短信不足';
            }
        } else {
            $msg = '获取剩余短信失败';
        }
        $this->writeSmslog($sdf['phones'], $sdf['content'], $msg, 0);
        return $info;
    }

    public function getServerTime() {
        static $serverTimestamp, $localTimestamp;
        if (null === $serverTimestamp || null === $localTimestamp) {
            $param = array(
                'certi_app' => 'sms.servertime',
                'version' => '1.0',
                'format' => 'json',
            );
            $param['certi_ac'] = $this->makeShopexAc($param, 'SMS_TIME');
            $result = $this->requestCall(SMS_SERVER_TIME, $param);
            $serverTimestamp = ('succ' == $result['rsp']) ? $result['data'] : time();
            $localTimestamp = time();
            return $serverTimestamp;
        } else {
            return $serverTimestamp + time() - $localTimestamp;
        }
    }

    public function getUserInfo() {
        $account = $this->__channelObj->channel['account'];
        $param = array(
            'certi_app' => 'sms.info',
            'entId' => $account['entid'],
            'entPwd' => md5($account['password'] . 'ShopEXUser'),
            'source' => APP_SOURCE,
            'version' => '1.0',
            'format' => 'json',
            'timestamp' => $this->getServerTime(),
        );

        $param['certi_ac'] = $this->baseMakeShopexAc($param, APP_TOKEN);
        $result = $this->requestCall(SMS_USER_INFO, $param);
       
        return $result;
    }

    public function newOauth($sdf) {
        $name = $sdf['sms_sign'];
        $sms_signObj = app::get('taoexlib')->model('sms_sign');
        $sms_sign = $sms_signObj->dump(array('name'=>$name),'*');
        if (!$sms_sign || $sms_sign['extend_no']=='') {
            $account = $this->__channelObj->channel['account'];
            $params = array(
                'shopexid' => $account['entid'],
                'passwd' => md5($account['password'] . 'ShopEXUser'),
                'content' => $name,
                'client_id' => 'n4v7d32k',
                'secret' => '6kcft2jbr5c7xiyoo7mz',
                'signUrl' => false
            );
           
            $result = $this->requestCall(SMS_NEW_OAUTH, $params);

            if ($result['rsp'] == 'succ') {
                $extend_no = $result['data']['extend_no'];
                $sign_data = array(
                    'name'  =>$name,
                    'extend_no'=>$extend_no,
                );
                if ($sms_sign && $extend_no) {
                    $sms_signObj->db->exec("UPDATE sdb_taoexlib_sms_sign SET extend_no='".$extend_no."' WHERE s_id=".$sms_sign['s_id']);
                }else{
                    $sms_signObj->save($sign_data);
                }
            }
            return $result;
        }
        return true;
    }

    public function sendByTmpl($sdf) {
        $account = $this->__channelObj->channel['account'];
        $params = array(
            'tplid'     =>  $sdf['tplid'],
            'product'   =>  APP_SOURCE,
            'phones'    =>  $sdf['phones'],
            'replace'   =>  json_encode($sdf['replace']),
            'timestamp' =>  strval($this->getServerTime()),
            'license'   =>  base_certificate::get('certificate_id') ? base_certificate::get('certificate_id') : 1,
            'entid'     =>  $account['entid'],
            'entpwd'    =>  md5($account['password'] . 'ShopEXUser'),
            'use_reply'=>'',
            'use_backlist'=>'',
            'signUrl' => true
        );
        #client 中的补齐参数
        $params['client_id'] = '7F97Z0'; //$key
        $params['secret'] = '76MASB5G3X3A199LAQOV';  //$secret
        $result = $this->requestCall(SMS_SEND_TMPL, $params);
       
        $this->sendSMSBack($result, $sdf);
        return $result;
    }
}